<template>
  <div class="time-tool">
    <el-card class="tool-card">
      <template #header>
        <div class="card-header">
          <span>时间工具</span>
          <div class="header-actions">
            <el-button type="primary" @click="getCurrentTime">
              <el-icon><Clock /></el-icon>
              获取当前时间
            </el-button>
            <el-button @click="clearAll">
              <el-icon><Delete /></el-icon>
              清空
            </el-button>
          </div>
        </div>
      </template>

      <div class="time-container">
        <!-- 时间戳转日期 -->
        <div class="converter-section">
          <div class="section-header">
            <h4>时间戳转日期</h4>
          </div>
          <el-input
            v-model="timestampInput"
            placeholder="请输入时间戳（支持10位秒级或13位毫秒级）"
            clearable
            @input="convertTimestampToDate"
            class="time-input"
          >
            <template #prepend>时间戳</template>
          </el-input>
          <div v-if="timestampResult" class="result-display">
            <div class="result-item">
              <span class="label">格式化时间：</span>
              <span class="value">{{ timestampResult.formatted }}</span>
              <el-button size="small" text @click="copyToClipboard(timestampResult.formatted)">
                <el-icon><CopyDocument /></el-icon>
              </el-button>
            </div>
            <div class="result-item">
              <span class="label">ISO字符串：</span>
              <span class="value">{{ timestampResult.iso }}</span>
              <el-button size="small" text @click="copyToClipboard(timestampResult.iso)">
                <el-icon><CopyDocument /></el-icon>
              </el-button>
            </div>
            <div class="result-item">
              <span class="label">相对时间：</span>
              <span class="value">{{ timestampResult.relative }}</span>
            </div>
          </div>
        </div>

        <!-- 日期转时间戳 -->
        <div class="converter-section">
          <div class="section-header">
            <h4>日期转时间戳</h4>
          </div>
          <el-date-picker
            v-model="dateInput"
            type="datetime"
            placeholder="请选择日期时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="convertDateToTimestamp"
            class="time-input"
            style="width: 100%"
          />
          <div v-if="dateResult" class="result-display">
            <div class="result-item">
              <span class="label">秒级时间戳：</span>
              <span class="value">{{ dateResult.seconds }}</span>
              <el-button size="small" text @click="copyToClipboard(dateResult.seconds.toString())">
                <el-icon><CopyDocument /></el-icon>
              </el-button>
            </div>
            <div class="result-item">
              <span class="label">毫秒级时间戳：</span>
              <span class="value">{{ dateResult.milliseconds }}</span>
              <el-button size="small" text @click="copyToClipboard(dateResult.milliseconds.toString())">
                <el-icon><CopyDocument /></el-icon>
              </el-button>
            </div>
          </div>
        </div>

        <!-- 当前时间信息 -->
        <div class="converter-section">
          <div class="section-header">
            <h4>当前时间信息</h4>
            <el-button size="small" text @click="updateCurrentTime">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
          <div v-if="currentTimeInfo" class="result-display">
            <div class="result-item">
              <span class="label">当前时间：</span>
              <span class="value">{{ currentTimeInfo.formatted }}</span>
              <el-button size="small" text @click="copyToClipboard(currentTimeInfo.formatted)">
                <el-icon><CopyDocument /></el-icon>
              </el-button>
            </div>
            <div class="result-item">
              <span class="label">秒级时间戳：</span>
              <span class="value">{{ currentTimeInfo.seconds }}</span>
              <el-button size="small" text @click="copyToClipboard(currentTimeInfo.seconds.toString())">
                <el-icon><CopyDocument /></el-icon>
              </el-button>
            </div>
            <div class="result-item">
              <span class="label">毫秒级时间戳：</span>
              <span class="value">{{ currentTimeInfo.milliseconds }}</span>
              <el-button size="small" text @click="copyToClipboard(currentTimeInfo.milliseconds.toString())">
                <el-icon><CopyDocument /></el-icon>
              </el-button>
            </div>
            <div class="result-item">
              <span class="label">UTC时间：</span>
              <span class="value">{{ currentTimeInfo.utc }}</span>
              <el-button size="small" text @click="copyToClipboard(currentTimeInfo.utc)">
                <el-icon><CopyDocument /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 功能说明 -->
      <div class="help-section">
        <el-collapse>
          <el-collapse-item title="功能说明" name="help">
            <div class="help-content">
              <p><strong>时间戳转日期：</strong>支持10位秒级时间戳和13位毫秒级时间戳转换为可读日期格式。</p>
              <p><strong>日期转时间戳：</strong>选择日期时间转换为秒级和毫秒级时间戳。</p>
              <p><strong>当前时间：</strong>获取当前时间的多种格式表示。</p>
              <p><strong>相对时间：</strong>显示相对于当前时间的时间差（如"3小时前"）。</p>
              <p><strong>快捷复制：</strong>点击复制按钮快速复制结果到剪贴板。</p>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Clock, 
  Delete, 
  CopyDocument, 
  Refresh 
} from '@element-plus/icons-vue'

const timestampInput = ref('')
const dateInput = ref('')
const timestampResult = ref<{
  formatted: string
  iso: string
  relative: string
} | null>(null)
const dateResult = ref<{
  seconds: number
  milliseconds: number
} | null>(null)
const currentTimeInfo = ref<{
  formatted: string
  seconds: number
  milliseconds: number
  utc: string
} | null>(null)

// 时间戳转日期
const convertTimestampToDate = () => {
  if (!timestampInput.value.trim()) {
    timestampResult.value = null
    return
  }

  try {
    let timestamp = parseInt(timestampInput.value)
    
    // 判断是秒级还是毫秒级时间戳
    if (timestamp.toString().length === 10) {
      timestamp = timestamp * 1000 // 转换为毫秒
    } else if (timestamp.toString().length !== 13) {
      throw new Error('时间戳格式不正确')
    }

    const date = new Date(timestamp)
    
    if (isNaN(date.getTime())) {
      throw new Error('无效的时间戳')
    }

    timestampResult.value = {
      formatted: formatDate(date),
      iso: date.toISOString(),
      relative: getRelativeTime(date)
    }
  } catch (error) {
    timestampResult.value = null
    ElMessage.error('时间戳格式错误: ' + (error as Error).message)
  }
}

// 日期转时间戳
const convertDateToTimestamp = () => {
  if (!dateInput.value) {
    dateResult.value = null
    return
  }

  try {
    const date = new Date(dateInput.value)
    const milliseconds = date.getTime()
    const seconds = Math.floor(milliseconds / 1000)

    dateResult.value = {
      seconds,
      milliseconds
    }
  } catch (error) {
    dateResult.value = null
    ElMessage.error('日期格式错误')
  }
}

// 获取当前时间
const getCurrentTime = () => {
  updateCurrentTime()
  ElMessage.success('已获取当前时间')
}

// 更新当前时间信息
const updateCurrentTime = () => {
  const now = new Date()
  const milliseconds = now.getTime()
  const seconds = Math.floor(milliseconds / 1000)

  currentTimeInfo.value = {
    formatted: formatDate(now),
    seconds,
    milliseconds,
    utc: now.toUTCString()
  }
}

// 格式化日期
const formatDate = (date: Date): string => {
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })
}

// 获取相对时间
const getRelativeTime = (date: Date): string => {
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffSec = Math.floor(diffMs / 1000)
  const diffMin = Math.floor(diffSec / 60)
  const diffHour = Math.floor(diffMin / 60)
  const diffDay = Math.floor(diffHour / 24)

  if (diffMs < 0) {
    const absDiffSec = Math.abs(diffSec)
    const absDiffMin = Math.abs(diffMin)
    const absDiffHour = Math.abs(diffHour)
    const absDiffDay = Math.abs(diffDay)

    if (absDiffDay > 0) return `${absDiffDay}天后`
    if (absDiffHour > 0) return `${absDiffHour}小时后`
    if (absDiffMin > 0) return `${absDiffMin}分钟后`
    return `${absDiffSec}秒后`
  }

  if (diffDay > 0) return `${diffDay}天前`
  if (diffHour > 0) return `${diffHour}小时前`
  if (diffMin > 0) return `${diffMin}分钟前`
  if (diffSec > 0) return `${diffSec}秒前`
  return '刚刚'
}

// 清空所有内容
const clearAll = () => {
  timestampInput.value = ''
  dateInput.value = ''
  timestampResult.value = null
  dateResult.value = null
  ElMessage.info('已清空所有内容')
}

// 复制到剪贴板
const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

// 组件挂载时获取当前时间
onMounted(() => {
  updateCurrentTime()
})
</script>

<style scoped>
.time-tool {
  max-width: 100%;
  background: transparent;
}

.tool-card {
  height: fit-content;
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-light);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.time-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
  margin-bottom: 20px;
}

.converter-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 20px;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  background: var(--el-fill-color-lighter);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.section-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.time-input {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
}

.time-input :deep(.el-input__inner) {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
}

.result-display {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-top: 16px;
}

.result-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-light);
  border-radius: 6px;
  transition: all 0.3s ease;
}

.result-item:hover {
  border-color: var(--el-color-primary-light-7);
  background: var(--el-color-primary-light-9);
}

.result-item .label {
  font-weight: 500;
  color: var(--el-text-color-regular);
  white-space: nowrap;
  min-width: 120px;
}

.result-item .value {
  flex: 1;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  color: var(--el-text-color-primary);
  word-break: break-all;
}

.help-section {
  border-top: 1px solid var(--el-border-color-lighter);
  padding-top: 20px;
}

.help-content {
  color: var(--el-text-color-regular);
  line-height: 1.6;
}

.help-content p {
  margin: 8px 0;
}

.help-content strong {
  color: var(--el-text-color-primary);
  font-weight: 600;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    flex-wrap: wrap;
  }
  
  .header-actions .el-button {
    flex: 1;
    min-width: 120px;
  }
  
  .result-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .result-item .label {
    min-width: auto;
  }
  
  .converter-section {
    padding: 16px;
  }
}

/* 深色模式适配 */
.dark .tool-card {
  background: var(--el-bg-color);
  border-color: var(--el-border-color);
}

.dark .converter-section {
  background: var(--el-fill-color-darker);
  border-color: var(--el-border-color);
}

.dark .result-item {
  background: var(--el-fill-color-dark);
  border-color: var(--el-border-color);
}

.dark .result-item:hover {
  border-color: var(--el-color-primary);
  background: var(--el-color-primary-dark-2);
}
</style>